package com.bid.base.common.util;
import jodd.util.ArraysUtil;

import javax.servlet.http.HttpServletRequest;

import java.util.Collection;
import java.util.Collections;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
/**
 * <strong>Description : </strong> <br>
 * <p>
 * <strong>北京正源德标科技信息有限责任公司</strong> <br>
 * </p>
 * <br>
 *
 * @author : zhaots
 * @date Date : 2020年12月07日 18:22
 * 修改人 修改日期 修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
public class Stringer {

    public static final String SEPARATOR_CAHR = new String(new byte[]{0x02});

    public static final String SEPARATOR_UNDERLINE = "_";

    public static final String DEFAULT_CHARSET = "UTF-8";


    public static void main(String[] args) {
        System.out.println(new Integer(2).toString());
//        Integer a =null;
////        boolean nullOrEmpty = isNullOrEmpty(a);
////        isNullOrEmpty(a);
//        boolean nullOrEmpty = isNullOrEmpty(SEPARATOR_CAHR, null);
//        System.out.println( isNullOrEmpty(SEPARATOR_CAHR));
////        String longChar = "aa" + SEPARATOR_CAHR + "bb";
////        System.out.println(longChar);
////        String[] split = longChar.split(SEPARATOR_CAHR);
////        System.out.println("123:" + ArraysUtil.toString(split));

    }


    public static String getIpAdrress(HttpServletRequest request){
        return getIpAdrress(request,false);
    }
    /**
     * 获取Ip地址
     * @param request
     * @return
     */
    public static String getIpAdrress(HttpServletRequest request,boolean all) {
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");
        if(!isNullOrEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if(index != -1){
                return all?XFor:XFor.substring(0,index);
            }else{
                return XFor;
            }
        }
        XFor = Xip;
        if(!isNullOrEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            return XFor;
        }
        if (isNullOrEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (isNullOrEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (isNullOrEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (isNullOrEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (isNullOrEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        if(XFor.equals("0:0:0:0:0:0:0:1")){
        	return "127.0.0.1";
        }
        return XFor;
    }

    /**
     * @author by  Jun 18, 2015
     *
     * @desc 获取本机IP，默认取出第一个有效的网卡ip（单网卡）.
     * @return
     */
    public static String getLocalIP() {
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        byte[] ipAddr = addr.getAddress();
        String ipAddrStr = "";
        for (int i = 0; i < ipAddr.length; i++) {
            if (i > 0) {
                ipAddrStr += ".";
            }
            ipAddrStr += ipAddr[i] & 0xFF;
        }
//        log.d("##>>>getLocalIP..."+ipAddrStr);
        return ipAddrStr;
    }

    public static String getLocalHostName() {
        String hostName;
        try {
            InetAddress addr = InetAddress.getLocalHost();
            hostName = addr.getHostName();
        } catch (Exception ex) {
            hostName = "";
        }
//        log.d("##>>>getLocalHostName..."+hostName);
        return hostName;
    }
    /**
     *
     * @author by  Jun 18, 2015
     *
     * @desc 获取本机所有IP（多网卡）.
     * @return
     */
    public static String[] getAllLocalHostIP() {
        String[] ret = null;
        try {
            String hostName = getLocalHostName();
            if (hostName.length() > 0) {
                InetAddress[] addrs = InetAddress.getAllByName(hostName);
                if (addrs.length > 0) {
                    ret = new String[addrs.length];
                    for (int i = 0; i < addrs.length; i++) {
                        ret[i] = addrs[i].getHostAddress();
                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            ret = null;
        }
//        logs.d("##>>>getAllLocalHostIP..."+ret.toString());
        return ret;
    }

    /**
     * @author by  Jun 18, 2015
     *
     * @desc 获取所有网卡ip信息.
     * @return
     */
    public static List<String> getAllNetIP() {
        List<String> ips = new ArrayList<String>();
        try {
            Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netint : Collections.list(nets))
                if (null != netint.getHardwareAddress()) {
                    List<InterfaceAddress> list = netint.getInterfaceAddresses();
                    for (InterfaceAddress interfaceAddress : list) {
                        String localip = interfaceAddress.getAddress().toString();
                        ips.add(localip);
                    }
                }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        logs.d("##>>>getAllNetIP..."+ips.toString());
        return ips;
    }
    public static String getClientIpAddrFromReq(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
//		logs.d("##>>>getClientIpAddr..."+ip);
        return ip;
    }

    public static String null2EmptyStr(Object obj) {
        if(isNullOrEmpty(obj)){
            return "";
        }
        return obj.toString();
    }


    public static boolean isNullOrEmpty(Object... objs) {
        boolean res = true;
        for (Object obj:objs) {
            res = isNullOrEmpty(obj);
            if(res){
                break;
            }
        }
        return res;
    }

    public static boolean isNullOrEmpty(Object obj) {

        boolean result = true;
        if (obj == null) {
            return true;
        }
        if (obj instanceof String) {
            result = (obj.toString().trim().length() == 0) || obj.toString().trim().equals("null");
        } else if (obj instanceof Collection) {
            result = ((Collection<?>) obj).size() == 0;
        } else if (obj instanceof Map) {
            result = ((java.util.Map<?,?>) obj).isEmpty();
        }else if (obj instanceof Object[]) {
             result = ((Object[]) obj).length == 0;
        }else if(obj instanceof Long){
        	result = ((Long) obj)==0l;
        }  else {
            result = ((obj == null) || (obj.toString().trim().length() < 1)) ? true : false;
        }
        return result;
    }

    public static boolean isImgSuffix(String suffix) {
        Pattern compile = Pattern.compile("^\\.(jpg|gif|png|bmp|jpeg|JPG|GIF|PNG|BMP|JPEG)$");
        Matcher matcher = compile.matcher(suffix);
        return matcher.matches();
    }

    public static String format(Date date, String pattern) {
        String returnValue = "";
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            returnValue = df.format(date);
        }
        return (returnValue);
    }
    public static String getNow(String format) {
        return format(new Date(), format);
    }

    public static int getFormTypeCount(String chkStr){
    	int count=0;
    	Pattern p1 = Pattern.compile("[a-zA-Z]+");
		if(p1.matcher(chkStr).find()){
			count++;
		}
		Pattern p2 = Pattern.compile("[0-9]+");
		if(p2.matcher(chkStr).find()){
			count++;
		}
    	return count;
    }

//    public static void main(String[] args) {
////    	String[] arr=new String[]{"abcdefg","abcabcabc","ABCdefGH","a123456","12345678"
////    			,"qwertyui","ZAQ!xsw2","3EDC4rfv","6yhn7UJM","xiaoming@passiontec"
////    			,"xiaoming1!@#","password","passw0rd","p@ssw0rd","admin1234"};
////    	List<String> asList = Arrays.asList(arr);
////    	System.out.println(asList.contains("test"));
////    	System.out.println(asList);
////    	String pwd="passw0rd";
////    	String encode = Base64.encode(pwd.getBytes(Charset.forName("UTF-8")));
////    	System.out.println("12345"+encode);
////    	System.out.println(getFormTypeCount("px123456"));
//    	System.out.println(isNullOrEmpty(0l));
//
//	}
	public static String getClientIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		//jlog.debug("##>>>getClientIpAddr..."+ip);
		return ip;
	}
}
